//
//  JCUserAccount.swift
//  SinaWeibo_18
//
//  Created by mac on 15/10/12.
//  Copyright © 2015年 cz. All rights reserved.
//

import UIKit
//用户账户信息
class JCUserAccount: NSObject,NSCoding {
    //访问令牌
    var access_token: String?
    //过期时间
    var expires_in: NSTimeInterval = 0 {
        didSet{
            //设置过期日期的值
            let nowDate = NSDate()
            expires_date = nowDate.dateByAddingTimeInterval(expires_in)
        }
    }
    //过期日期
    var expires_date: NSDate?
    
    var remind_in: String?
    var uid: String?
    
    //用户头像地址 大图
    var avatar_large: String?
    //用户名称
    var screen_name: String?
    
    init(dict:[String : AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }
    
    //设置路径
    static let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archive")
    
    //保存当前账户对象
    func saveUserAccount(){
        printLog("归档路径:\(JCUserAccount.path)")
        NSKeyedArchiver.archiveRootObject(self, toFile: JCUserAccount.path)
    }
    // MARK: - 读取当前账户对象
    class func loadUserAccount() -> JCUserAccount? {
        //解档,读取
     let account = NSKeyedUnarchiver.unarchiveObjectWithFile(self.path) as? JCUserAccount
        //判断accessToken访问令牌是否过期
        if let acc = account {
            //未过期
            if acc.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return acc
            }
        }
        
        return account
    }
    
    
    //告诉系统归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        aCoder.encodeObject(remind_in, forKey: "remind_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        
    }
    //告诉系统解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        remind_in = aDecoder.decodeObjectForKey("remind_in") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
    }
    
    
    
    
    //重写description方法
    override var description : String{
        let keys = ["access_token","expires_in","remind_in","uid","avatar_large","screen_name"]
        return dictionaryWithValuesForKeys(keys).description
    }
}
